import { Request, Response, NextFunction } from 'express'
import { AppError, sendError, createInternalError } from '../utils/errors'

// 全局错误处理中间件
export const errorHandler = (error: Error, req: Request, res: Response, _next: NextFunction) => {
  // 记录错误日志
  console.error('错误详情:', {
    message: error.message,
    stack: error.stack,
    url: req.url,
    method: req.method,
    body: req.body,
    query: req.query,
    timestamp: new Date().toISOString()
  })

  // 如果是自定义错误，直接发送
  if (error instanceof AppError) {
    sendError(res, error)
    return
  }

  // Prisma 错误处理
  if (error.constructor.name === 'PrismaClientKnownRequestError') {
    const prismaError = error as any
    if (prismaError.code === 'P2002') {
      // 唯一约束冲突
      const appError = createInternalError('数据已存在，请检查输入')
      sendError(res, appError)
      return
    }
    if (prismaError.code === 'P2025') {
      // 记录不存在
      const appError = createInternalError('请求的数据不存在')
      sendError(res, appError)
      return
    }
  }

  // 其他未知错误
  const internalError = createInternalError(
    process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
  )
  sendError(res, internalError)
}

// 404 错误处理中间件
export const notFoundHandler = (req: Request, res: Response) => {
  res.status(404).json({
    success: false,
    error: {
      code: 'NOT_FOUND',
      message: '接口不存在',
      details: {
        url: req.url,
        method: req.method
      }
    }
  })
}

// 请求日志中间件
export const requestLogger = (req: Request, res: Response, next: NextFunction) => {
  const start = Date.now()
  
  // 记录请求开始
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - 开始处理`)
  
  // 监听响应结束
  res.on('finish', () => {
    const duration = Date.now() - start
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - ${res.statusCode} - ${duration}ms`)
  })
  
  next()
}
